/*
 * @Description:
 * @Version: 1.0
 * @Autor: zenghao
 * @Date: 2023-11-30 14:48:24
 * @LastEditors: zenghao
 * @LastEditTime: 2023-12-06 15:16:04
 */
import { fileURLToPath, URL } from "node:url";

import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";

// import { visualizer } from 'rollup-plugin-visualizer'


// API自动引入插件
import AutoImport from "unplugin-auto-import/vite";
// 组件自动引入插件
import Components from "unplugin-vue-components/vite";
// ArcoVue、VueUse 组件和指令自动引入解析器
import {
  ArcoResolver,
  VueUseComponentsResolver,
  VueUseDirectiveResolver,
} from "unplugin-vue-components/resolvers";
// icon 插件
import Icons from "unplugin-icons/vite";
// icon 自动引入解析器
import IconsResolver from "unplugin-icons/resolver";
// icon 加载 loader
import { FileSystemIconLoader } from "unplugin-icons/loaders";
// Unocss 插件
import Unocss from "unocss/vite";
// Unocss 默认预设
import presetUno from "@unocss/preset-uno";
// Unocss 属性模式预设
import presetAttributify from "@unocss/preset-attributify";
// Unocss 指令插件
import transformerDirective from "@unocss/transformer-directives";

import viteCompression from "vite-plugin-compression";

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const viteEnv = loadEnv(mode, "./");
  return {
    base: viteEnv.VITE_BASE,
    // base: path.resolve(__dirname, './dist'),
    server: {
      host: "0.0.0.0",
      port: "3002",
      open: true,
      // 端口占用直接退出
      strictPort: true,
      // 本地服务 CORS 是否开启
      cors: true,
      proxy: {
        '/api': {
          target: viteEnv.VITE_BASE_SERVER_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(viteEnv.VITE_BASE_API, "/"),
        },
        '/file': {
          target: viteEnv.VITE_BASE_SERVER_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(viteEnv.VITE_BASE_FILE_URL, "/"),
        },
        '/server': {
          target: viteEnv.VITE_BASE_SERVER_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(viteEnv.VITE_BASE_SERVER_API, "/"),
        },
        '/eurka': {
          target: viteEnv.VITE_BASE_SERVER_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(viteEnv.VITE_BASE_EURKA_API, "/"),
        }
      },
      hmr: {
        overlay: false // https://www.ifrontend.net/2023/05/vite-common-problem/
      }
    },
    build: {
      outDir: "hundsun-tools-web",
      assetsDir: "static/assets",
      terserOptions: {
        compress: {
          drop_console: true, // 生产环境去掉控制台 console
          drop_debugger: true, // 生产环境去掉控制台 debugger 默认就是true
          dead_code: true, // 删除无法访问的代码 默认就是true
        }
      },
      sourcemap: true,
      // 规定触发警告的 chunk 大小，消除打包大小超过500kb警告
      chunkSizeWarningLimit: 2000,
      // 静态资源打包到dist下的不同目录
      rollupOptions: {
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
        },
      },
    },
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        "Assets": fileURLToPath(new URL("./src/assets", import.meta.url)),
      },
    },
    plugins: [
      vue(),
      // visualizer({open: true}),
      viteCompression({
        verbose: true, // 是否在控制台输出压缩结果
        disable: false, // 是否禁用,相当于开关在这里
        threshold: 10240, // 体积大于 threshold 才会被压缩,单位 b，1b=8B, 1B=1024KB  那我们这里相当于 9kb多吧，就会压缩
        algorithm: "gzip", // 压缩算法,可选 [ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
        ext: ".gz", //文件后缀
        // deleteOriginFile: true
      }),
      // 使用Unocss
      Unocss({
        // 预设
        presets: [presetUno(), presetAttributify()],
        // 指令转换插件
        transformers: [transformerDirective()],
        // 自定义规则
        rules: [],
      }),
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/, // .md
        ],
        imports: ["vue", "pinia", "vue-router", "@vueuse/core"],
        // 生成相应的自动导入json文件。
        // eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
        eslintrc: {
          enabled: true,
          filepath: "./.eslintrc-auto-import.json", // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        },
        resolvers: [ArcoResolver()],
      }),
      Components({
        // imports 指定组件所在位置，默认为 src/components
        dirs: ["src/components/", "src/view/", "src/layout"],
        include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
        resolvers: [
          ArcoResolver({
            sideEffect: true,
          }),
          VueUseComponentsResolver(),
          VueUseDirectiveResolver(),
          IconsResolver({
            // icon自动引入的组件前缀 - 为了统一组件icon组件名称格式
            prefix: "icon",
            // 自定义的icon模块集合
            customCollections: ["user", "home"],
          }),
        ],
      }),
      Icons({
        compiler: "vue3",
        customCollections: {
          // user图标集，给svg文件设置fill="currentColor"属性，使图标的颜色具有适应性
          user: FileSystemIconLoader("src/assets/svg/user", (svg) =>
            svg.replace(/^<svg /, '<svg fill="currentColor" ')
          ),
          // home 模块图标集
          home: FileSystemIconLoader("src/assets/svg/home", (svg) =>
            svg.replace(/^<svg /, '<svg fill="currentColor" ')
          ),
        },
        autoInstall: true,
      }),
    ],
  };
});
